package com.fengxu.gamescript.ui.main.mode.doc

import android.annotation.SuppressLint
import android.content.ClipboardManager
import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.webkit.JavascriptInterface
import android.webkit.WebView
import androidx.core.content.ContextCompat.getSystemService
import androidx.fragment.app.Fragment
import com.fengxu.gamescript.R
import com.fengxu.gamescript.ui.main.MainActivity
import com.fengxu.gamescript.util.CommonUtils
import com.scwang.smartrefresh.layout.SmartRefreshLayout
import com.xuexiang.xui.widget.dialog.materialdialog.MaterialDialog
import org.jetbrains.anko.support.v4.toast
import kotlin.properties.Delegates


/**
 * 教程页面
 */
@SuppressLint("JavascriptInterface")
class DocFragment : Fragment() {

    private var isInit = false

    private val webView:WebView by lazy { requireActivity().findViewById(R.id.doc_webview) }

    private var loadingDialog: MaterialDialog by Delegates.notNull()

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_doc, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        // 初始化webView
        webView.settings.javaScriptEnabled = true
        webView.settings.domStorageEnabled = true
        webView.addJavascriptInterface(this, "android")
        (requireActivity() as MainActivity).tabSelectChangeEvents.add(this::tabChanged)
        // 添加刷新事件
        val smartRefreshLayout = requireActivity().findViewById<SmartRefreshLayout>(R.id.doc_smartRefresh)
        smartRefreshLayout.setOnRefreshListener {
            loadWebView()
            smartRefreshLayout.finishRefresh()
        }
    }

    // tab选项改变事件
    private fun tabChanged(index: Int){
        if(index == 1 && !isInit){
            loadWebView(true)
            isInit = true
        }
    }

    /**
     * 加载教程文档
     */
    @JavascriptInterface
    fun loadDoc():String{
        val bytes = requireActivity().assets.open("doc/api.md").readBytes()
        return String(bytes)
    }

    /**
     * 加载完成
     */
    @JavascriptInterface
    fun loadComplete(){
        loadingDialog?.dismiss()
    }


    /**
     * webView加载网页
     * @param 是否显示加载弹窗
     */
    private fun loadWebView(showLoading: Boolean = false){
        if(showLoading){
            loadingDialog = CommonUtils.loadingDialog(requireContext())
        }
        webView.loadUrl("file:///android_asset/doc/index.html")
    }

}